/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.DocumentTemplateTypeEnum;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.common.utils.ImageUtil;
import com.icinfo.cloud.provider.common.utils.PdfTransferImageUtil;
import com.icinfo.cloud.provider.common.utils.PdfUtil;
import com.icinfo.cloud.provider.exception.BusinessException;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.FillAndConvertToPdfRequest;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonHtmlRequest;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonPreviewDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.vo.DocumentCommonFormDataVo;
import com.icinfo.cloud.provider.punish.common.documentoperate.vo.DocumentCommonFormHtmlVo;
import com.icinfo.cloud.provider.punish.common.seal.dto.FileSealInfoQueryDto;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.document.dto.PrintDocumentBuildDto;
import com.icinfo.cloud.provider.punish.dto.PrintDocHtmlQueryDto;
import com.icinfo.cloud.provider.punish.dto.PrintDocQueryDto;
import com.icinfo.cloud.provider.punish.mapper.AppCaseBeforeDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.mapper.CaseDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.mapper.CaseMainInfoMapper;
import com.icinfo.cloud.provider.punish.model.AppCaseBeforeDocumentRecordNew;
import com.icinfo.cloud.provider.punish.print.vo.PrintDocumentVo;
import com.icinfo.cloud.provider.punish.service.IAppCaseBeforeDocumentRecordService;
import com.icinfo.cloud.provider.punish.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.service.IDocCommonOperateService;
import com.icinfo.cloud.provider.punish.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.strategy.document.BaseDocumentParam;
import com.icinfo.cloud.provider.punish.strategy.document.enums.DocumentParamEnum;
import com.icinfo.cloud.provider.punish.strategy.document.util.DocumentParamUtil;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseTemporarySaveDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.tools.utils.MapUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * 描述: 文书发送记录 document_send_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年03月30日
 */
@Service
@Slf4j
public class DocCommonOperateServiceImpl extends MyBatisServiceSupport implements IDocCommonOperateService {
    @Value("${document.url}")
    private String documentUrl;
    @Value("${document.api.getAssembleDocHtmlContent}")
    private String getAssembleDocHtmlContent;
    @Value("${tzService.url}")
    private String url;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private IAppCaseBeforeDocumentRecordService appCaseBeforeDocumentRecordService;
    @Resource
    private AppCaseBeforeDocumentRecordMapper appCaseBeforeDocumentRecordMapper;
    private static final String IMG_QR_CODE_URL = "qrCodeUrl";
    private static final String IMG_BAR_CODE_URL = "barCodeUrl";
    @Resource
    private ISysDepartParamService sysDepartParamService;

    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;

    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;

    @Resource
    private ApplicationContext applicationContext;

    @Override
    public String getPrintDocHtmlContent(PrintDocHtmlQueryDto queryDto) {
        UserDTO userDTO = UserUtil.getUserInfo();
        String userId = userDTO.getUserId().toString();
        //String userId="12020908174520555";
        String printType = "textPrint";
       /* if("12020908174520555".equals(userId)||"12020908174520666".equals(userId)){
            printType="textPrint";
        }*/
        String htmlContent = "";
        if ("textPrint".equals(printType)) {
            //文字打印
            CaseDocumentRecord record = caseDocumentRecordMapper.selectByPrimaryKey(queryDto.getDocumentId());
            String documentCatalogCode = queryDto.getDocumentCatalogCode();
            FillAndConvertToPdfRequest request = new FillAndConvertToPdfRequest();
            JSONObject jsonObject;
            String templateCode = "";
            if (record != null) {
                jsonObject = JSON.parseObject(record.getDocumentContent());
                documentCatalogCode = record.getDocumentCatalogCode();
                templateCode = record.getDocumentTemplateCode();
            } else {
                AppCaseBeforeDocumentRecordNew appCaseBeforeDocumentRecordNew = appCaseBeforeDocumentRecordMapper.selectByPrimaryKey(queryDto.getDocumentId());
                if (ObjectUtil.isEmpty(appCaseBeforeDocumentRecordNew)) {
                    throw new BusinessException("文书信息不存在");
                }
                jsonObject = JSON.parseObject(appCaseBeforeDocumentRecordNew.getDocumentContent());
                documentCatalogCode = appCaseBeforeDocumentRecordNew.getDocumentCatalogCode();
            }
            //模板code为空从配置表里取templateCode
            if (ObjectUtil.isEmpty(templateCode)) {
                List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = appCaseBeforeDocumentRecordService.getConfigBusiParamDocumentInfos(documentCatalogCode);
                templateCode = getTemplateCodeByDocumentCatalogCode(configBusiParamDocumentInfos, "");
            }
            SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(userDTO.getOrgCode(), userDTO.getDeptCode());
            if (ObjectUtils.isEmpty(sysDepartParam)) {
                throw new BusinessException("未获取到单位参数配置信息，请配置");
            }
            JSONObject json = new JSONObject();
            json.put("uniscid", sysDepartParam.getUnicode());
            json.put("deptCode", userDTO.getDeptCode());
            Map<String, String> headers = HeaderUtil.headerInfo();
            String response = HttpUtil.createPost(url.concat("/punish/config/org/related/seal/getOrgRelatedSealConfigInfoByUniscidAndDeptCode")).addHeaders(headers).body(json.toJSONString()).execute().body();
            Result result = JSON.parseObject(response, Result.class);
            Map<String, Object> resultMap = JSONObject.parseObject(result.getData().toString(), Map.class);
            /*ConfigOrgRelatedSealVo configOrgRelatedSeal=result.getData();*/
            //String sealPdfUrl = "http://183.230.113.144:41130/fastdfs/group1/M00/00/3B/wKgC32S49T-AK_CDAAHY9tqgK2w450.pdf";
            String sealPdfUrl = MapUtils.getString(resultMap, "sealPdfUrl", "");
            if (StringUtils.isBlank(sealPdfUrl)) {
                throw new BusinessException("印章地址为空");
            }
            String sealPicBase64 = PdfTransferImageUtil.pdfTransImage(sealPdfUrl);
            jsonObject.put("sealBase64", sealPicBase64);
            jsonObject = dealDocumentContent(jsonObject);
            request.setParamMap(jsonObject);
            request.setTemplateCode(templateCode);
            htmlContent = getAssembleDocHtmlContent(request);
            //todo 暂时特殊处理图片
            htmlContent = htmlContent.replace("nofind();", "this.style.display='none'").replace("¥", "￥");
            return htmlContent;
        } else {
            //图片打印
            String printUrl = "";
            CaseDocumentRecord record = caseDocumentRecordMapper.selectByPrimaryKey(queryDto.getDocumentId());
            if (!ObjectUtils.isEmpty(record)) {
                if (StringUtils.isNotBlank(record.getDocumentUrlAfterSign())) {
                    printUrl = record.getDocumentUrlAfterSign();
                } else if (StringUtils.isNotBlank(record.getDocumentUrlAfterSeal())) {
                    printUrl = record.getDocumentUrlAfterSeal();
                } else {
                    printUrl = record.getDocumentUrl();
                }
            } else {
                AppCaseBeforeDocumentRecordNew appCaseBeforeDocumentRecordNew = appCaseBeforeDocumentRecordMapper.selectByPrimaryKey(queryDto.getDocumentId());
                if (ObjectUtil.isEmpty(appCaseBeforeDocumentRecordNew)) {
                    throw new BusinessException("文书信息不存在");
                }
                if (StringUtils.isNotBlank(appCaseBeforeDocumentRecordNew.getDocumentUrlAfterSign())) {
                    printUrl = appCaseBeforeDocumentRecordNew.getDocumentUrlAfterSign();
                } else if (StringUtils.isNotBlank(appCaseBeforeDocumentRecordNew.getDocumentUrlAfterSeal())) {
                    printUrl = appCaseBeforeDocumentRecordNew.getDocumentUrlAfterSeal();
                } else {
                    printUrl = appCaseBeforeDocumentRecordNew.getDocumentUrl();
                }
            }
            if (StringUtils.isBlank(printUrl)) {
                throw new BusinessException("文书地址不存在");
            }
            StringBuffer htmlContentStr = new StringBuffer();
            htmlContentStr.append("<html><body style='margin: 0px;'>");
            List<String> imgBase64List = PdfUtil.pdfTransMultipleImage(printUrl);

            if (!ObjectUtils.isEmpty(imgBase64List)) {
                for (String imgBase64 : imgBase64List) {
                    htmlContentStr.append("<img style='width:100%' src='" + imgBase64 + "' />");
                }
            }
            htmlContentStr.append("</body>" +
                    "</html>");
            System.out.println("htmlContent=======" + htmlContent.toString());
            htmlContent = htmlContentStr.toString();
            return htmlContent;
        }
    }

    /**
     * 处理html jsonobject
     *
     * @param jsonObject json对象
     * @return {@link JSONObject }
     * @author shishengyao
     * @date 2023/02/09
     */ //    @Override
//    public String getPrintDocHtmlContent(PrintDocHtmlQueryDto queryDto) {
//        long start = System.currentTimeMillis();
//        CaseDocumentRecord record = caseDocumentRecordMapper.selectByPrimaryKey(queryDto.getDocumentId());
//        String documentUrlPrint="";
//        String imageBase64Str="";
//        if(record!=null){
//            documentUrlPrint=record.getDocumentUrlPrint();
//            if (ObjectUtil.isEmpty(documentUrlPrint)){
//                documentUrlPrint = record.getDocumentUrl();
//            }
//            //转换成打印图片
//            if (documentUrlPrint.endsWith(".pdf")){
//                imageBase64Str  = PdfTransferImageUtil.pdfTransGrayImage(documentUrlPrint);
//                CaseDocumentRecord newRecord=new CaseDocumentRecord();
//                newRecord.setDocumentUrlPrint(imageBase64Str);
//                newRecord.setId(record.getId());
//                caseDocumentRecordMapper.updateByPrimaryKeySelective(newRecord);
//            }
//
//        }else {
//            AppCaseBeforeDocumentRecord appCaseBeforeDocumentRecord = appCaseBeforeDocumentRecordMapper.selectByPrimaryKey(queryDto.getDocumentId());
//            if (ObjectUtil.isEmpty(appCaseBeforeDocumentRecord)) {
//                throw new BusinessException("文书信息不存在");
//            }
//            documentUrlPrint = appCaseBeforeDocumentRecord.getDocumentUrlPrint();
//            if (ObjectUtil.isEmpty(documentUrlPrint)){
//                documentUrlPrint = appCaseBeforeDocumentRecord.getDocumentUrl();
//            }
//            imageBase64Str=  documentUrlPrint;
//            if (documentUrlPrint.endsWith(".pdf")){
//                imageBase64Str  = PdfTransferImageUtil.pdfTransGrayImage(documentUrlPrint);
//                AppCaseBeforeDocumentRecord newRecord=new AppCaseBeforeDocumentRecord();
//                newRecord.setDocumentUrlPrint(imageBase64Str);
//                newRecord.setId(appCaseBeforeDocumentRecord.getId());
//                appCaseBeforeDocumentRecordMapper.updateByPrimaryKeySelective(newRecord);
//            }
//        }
//
//        StringBuffer stringBuffer=new StringBuffer();
//        stringBuffer.append("<html><head><style><meta charset=\"UTF-8\" /> </style></head><body style=\"margin: 0 0 0 0;\">")
//                .append("<div style=\"height:15.3in;background-color: white;\">")
//                .append("<img src=\"")
//                .append(imageBase64Str)
//                .append("\"style=\"width: 100%;height:auto;max-height: 100%;max-width: 100%;\"/>")
//                .append("</div></body></html>");
//        System.out.println("签章耗时------------------------" + (System.currentTimeMillis() - start));
//        return stringBuffer.toString();
//    }
    @Override
    public String getPrintDoImage(PrintDocHtmlQueryDto queryDto) {
        CaseDocumentRecord record = caseDocumentRecordMapper.selectByPrimaryKey(queryDto.getDocumentId());
        String documentUrlAfterSign = "";
        if (record != null) {
            documentUrlAfterSign = record.getDocumentUrlAfterSign();
        } else {
            AppCaseBeforeDocumentRecordNew appCaseBeforeDocumentRecordNew = appCaseBeforeDocumentRecordMapper.selectByPrimaryKey(queryDto.getDocumentId());
            if (ObjectUtil.isEmpty(appCaseBeforeDocumentRecordNew)) {
                throw new BusinessException("文书信息不存在");
            }
            documentUrlAfterSign = appCaseBeforeDocumentRecordNew.getDocumentUrlAfterSign();

        }
        return PdfTransferImageUtil.pdfTransGrayImage(documentUrlAfterSign);
    }

    @Override
    public String getTemplateCodeByDocumentCatalogCode(List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos, String partyType) {
        String templateCode = "";
        if (ObjectUtil.isNotEmpty(configBusiParamDocumentInfos)) {
            //根据当事人类型获取对应的模板
            if (Constant.STRING_1.equals(partyType)) {
                //个人
                templateCode = configBusiParamDocumentInfos.get(0).getTemplatePersonCode();
            } else if (Constant.STRING_2.equals(partyType)) {
                //法人
                templateCode = configBusiParamDocumentInfos.get(0).getTemplateLegalCode();
            } else {
                templateCode = configBusiParamDocumentInfos.get(0).getTemplatePersonCode();
            }
        }
        return templateCode;
    }


    public String getAssembleDocHtmlContent(FillAndConvertToPdfRequest pdfRequest) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        Map<String, Object> paramMap = new HashMap<>(16);
        paramMap.put("templateCode", pdfRequest.getTemplateCode());
        paramMap.put("paramMap", pdfRequest.getParamMap());
        if (!ObjectUtils.isEmpty(pdfRequest.getTemplateType())) {
            paramMap.put("templateType", pdfRequest.getTemplateType());
        } else {
            paramMap.put("templateType", "narrow");
        }
        String result = HttpUtil.createPost(documentUrl.concat(getAssembleDocHtmlContent)).addHeaders(headers).body(JSON.toJSONString(paramMap)).contentType("application/json").execute().body();
        if (com.icinfo.framework.tools.utils.StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (Constant.INTEGER_200 == jsonObject.getIntValue(Constant.STRING_CODE_LOWER)) {
                String htmlContent = jsonObject.get("data").toString();
                return htmlContent;
            } else {
                throw new BusinessException(jsonObject.getString("message"));
            }
        } else {
            throw new BusinessException("文书生成服务网络异常");
        }
    }

    /**
     * 获取文书html公共方法
     *
     * @param request
     * @return
     */
    @Override
    public Result<DocumentCommonFormHtmlVo> getDocBaseInfo(StageDocCommonHtmlRequest request) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(request);
        String response = HttpUtil.createPost(url.concat("/punish/stagedoc/common/getDocBaseInfo")).addHeaders(headers).body(param).execute().body();
        Result<DocumentCommonFormHtmlVo> result = JSON.parseObject(response, Result.class);
        return result;
    }

    /**
     * 获取文书数据公共方法
     *
     * @param request
     * @return
     */
    @Override
    public Result<DocumentCommonFormDataVo> getDocFormData(StageDocCommonHtmlRequest request) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(request);
        String response = HttpUtil.createPost(url.concat("/punish/stagedoc/common/getDocFormData")).addHeaders(headers).body(param).execute().body();
        Result<DocumentCommonFormDataVo> result = JSON.parseObject(response, Result.class);
        return result;
    }

    /**
     * 描述：保存文书信息通用接口
     *
     * @param saveDto
     * @return
     */
    @Override
    public Result<Map<String, Object>> saveDocInfo(StageDocCommonOperateSaveDto saveDto) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(saveDto);
        String response = HttpUtil.createPost(url.concat("/punish/stagedoc/common/saveDocInfo")).addHeaders(headers).body(param).execute().body();
        Result<Map<String, Object>> result = JSON.parseObject(response, Result.class);
        return result;
    }

    /**
     * 预览文书接口
     *
     * @param previewDto
     * @return
     */
    @Override
    public Result<Map<String, Object>> docPreview(StageDocCommonPreviewDto previewDto) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(previewDto);
        String response = HttpUtil.createPost(url.concat("/punish/stagedoc/common/docPreview")).addHeaders(headers).body(param).execute().body();
        Result<Map<String, Object>> result = JSON.parseObject(response, Result.class);
        return result;
    }

    /**
     * 文书暂存功能--通用
     *
     * @param saveDto
     * @return
     */
    @Override
    public Result saveCaseReasonRecord(CaseTemporarySaveDto saveDto) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(saveDto);
        String response = HttpUtil.createPost(url.concat("/punish/ucase/temporary/saveTemporary")).addHeaders(headers).body(param).execute().body();
        Result<Map<String, Object>> result = JSON.parseObject(response, Result.class);
        return result;
    }

    @Override
    public PrintDocumentVo getPrintDocContent(PrintDocQueryDto dto) {
        switch (dto.getDocumentSource()) {
            case ZTC:
                return buildZtcPrintDocumentVo(dto);
            case CASE:
                return buildCasePrintDocumentVo(dto);
            default:
                throw new BusinessException("没有该种文书来源类型");
        }
    }

    /**
     * 构建案件打印文书
     *
     * @param dto
     * @return
     */
    private PrintDocumentVo buildCasePrintDocumentVo(PrintDocQueryDto dto) {
        CaseDocumentRecord documentRecord = caseDocumentRecordMapper.selectByPrimaryKey(dto.getDocumentId());
        if (Objects.isNull(documentRecord)) {
            throw new BusinessException("没有找到文书记录信息");
        }
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(documentRecord.getCaseId());
        if (Objects.isNull(caseMainInfo)) {
            throw new BusinessException("没有找到案件信息");
        }
        return buildPrintDocumentVo(dto, getTemplateTypeByCode(documentRecord.getDocumentTemplateType()),
                documentRecord.getDocumentCatalogCode(),
                documentRecord.getDocumentContent(), caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
    }

    private DocumentTemplateTypeEnum getTemplateTypeByCode(String code) {
        return Arrays.stream(DocumentTemplateTypeEnum.values()).filter(item -> item.getCode().equals(code))
                .findFirst().orElseThrow(() -> new BusinessException("没有找到对应的文书类型"));
    }

    /**
     * 构建直通车打印文书
     *
     * @param dto
     * @return
     */
    private PrintDocumentVo buildZtcPrintDocumentVo(PrintDocQueryDto dto) {
        AppCaseBeforeDocumentRecordNew documentRecord = appCaseBeforeDocumentRecordMapper.selectByPrimaryKey(dto.getDocumentId());
        if (Objects.isNull(documentRecord)) {
            throw new BusinessException("没有找到文书记录信息");
        }
        return buildPrintDocumentVo(dto, DocumentTemplateTypeEnum.NARROW_TEMPLATE, documentRecord.getDocumentCatalogCode(),
                documentRecord.getDocumentContent(), documentRecord.getOrgCode(), documentRecord.getDeptCode());
    }

    /**
     * 构建打印对象
     *
     * @param dto                 打印参数
     * @param templateType        文书类型
     * @param documentCatalogCode 文书catalogCode
     * @param documentContent     文书参数内容
     * @param orgCode             组织code
     * @param deptCode            部门code
     * @return
     */
    private PrintDocumentVo buildPrintDocumentVo(PrintDocQueryDto dto,
                                                 DocumentTemplateTypeEnum templateType,
                                                 String documentCatalogCode, String documentContent,
                                                 String orgCode, String deptCode) {
        //获取文书配置信息
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo =
                configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        DocumentKindEnum documentKind = DocumentKindEnum.parseByCode(configBusiParamDocumentInfo.getDocumentKindCode());
        //根据文书种类获取文书参数对象
        Class<? extends BaseDocumentParam> documentParamClass = DocumentParamEnum.getByKind(documentKind)
                .getParamEntityClass();
        BaseDocumentParam baseDocumentParam = ReflectUtil.newInstance(documentParamClass);
        //填充参数字段
        JSONObject params = JSON.parseObject(documentContent);
        if (DocumentTemplateTypeEnum.STANDARD_TEMPLATE.equals(templateType)) {
            //标准文书参数时，需要转换为窄幅的参数
            DocumentParamUtil.convertStandardToNarrow(params, documentParamClass);
        }
        baseDocumentParam.fillFieldByParams(DocumentTemplateTypeEnum.NARROW_TEMPLATE, params);
        //组装json返回
        return baseDocumentParam.assemblyPrintContent(new PrintDocumentBuildDto()
                .setDocumentId(dto.getDocumentId())
                .setDocumentCatalogCode(documentCatalogCode)
                .setSource(dto.getDocumentSource())
                .setOrgCode(orgCode)
                .setDeptCode(deptCode)
                .setApplicationContext(applicationContext)
                .setDocumentTemplateType(DocumentTemplateTypeEnum.NARROW_TEMPLATE)
                .setDocumentParam(params));
    }

    /**
     * @return java.lang.String 获取到签章的url
     * @Author xuzhimin
     * @Description 使用空白pdf模板获取签章
     * @Date 2023/8/21
     * @Param []
     **/
    @Override
    public String getSealPreviewInfo(String orgStandardNameSeal, String sealDate, String orgCode, String deptCode) {
        /*SealPreviewInfoRequest request = new SealPreviewInfoRequest();
        request.setSealCode("4");//目前该参数没用
        Result result = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_SEAL_PREVIEW_INFO, request);
        log.info("----------获取单位签章返回数据---"+JSONObject.toJSONString(result));
        if (result.getCode() != Result.DEFAULT_SUCCESS) {
            log.info("----------获取单位签章------报错---");
            throw new BusinessException(result.getMessage());
        }
        if(SpringContextUtil.checkIsPrdProfile()){
            return PdfUtil.pdfTransImage(ossCommonUtil.convertOssUrl(result.getData().toString(),true));
        }
        return PdfUtil.pdfTransImage(result.getData().toString());*/
        FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
        Map<String, Object> paramMap = new HashMap<>();
        Map<String, Object> paramMap1 = new HashMap<>();
        paramMap1.put("sealDate", sealDate);
        paramMap1.put("orgStandardNameSeal", orgStandardNameSeal);
        paramMap.put("templateCode", "DT2A0223300JYCXCFJQZ0000001");
        paramMap.put("paramMap", paramMap1);
        paramMap.put("templateType", "narrow");
        pdfRequest.setTemplateCode("DT2A0223300JYCXCFJQZ0000001");
        pdfRequest.setTemplateType("narrow");
        pdfRequest.setParamMap(paramMap1);
        //paramMap.put("isWatermark", pdfRequest.getIsWatermark());
        //paramMap.put("watermarkContent", pdfRequest.getWatermarkContent());
        Map<String, String> unSealPdfUrl = appCaseBeforeDocumentRecordService.getConvertedPdfUrl(pdfRequest);
        // 签字捺印
        FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(orgCode, deptCode);
        queryDto.setUniscid(sysDepartParam.getUnicode());
        queryDto.setFileBase64(unSealPdfUrl.get("fileBase64"));
        queryDto.setDeptCode(deptCode);
        String ossUrl = appCaseBeforeDocumentRecordService.dealFileSeal(queryDto);
        log.info("签章返回=>{}", ossUrl);
//        return PdfUtil.pdfTransImage(ossUrl);
        return ossUrl;
    }


    /**
     * 描述：处理模板的json数据
     *
     * @param jsonObject json对象
     * @return {@link JSONObject }
     * @author shishengyao
     * @date 2023/02/09
     */
    private JSONObject dealDocumentContent(JSONObject jsonObject) {
        try {
            //特殊处理捺印图片为灰色
            if (ObjectUtil.isNotEmpty(jsonObject.get("signFingerprintPic"))) {
                if (!jsonObject.getString("signFingerprintPic").startsWith("http")) {
                    jsonObject.put("signFingerprintPic", ImageUtil.binaryImage2(jsonObject.getString("signFingerprintPic")));
                } else {
                    jsonObject.put("signFingerprintPic", ImageUtil.binaryImage2(ImageUtil.imageUrlTransBase64(jsonObject.getString("signFingerprintPic"))));
                }
            }
            if (ObjectUtil.isNotEmpty(jsonObject.get("mainHandleSignPic"))) {
                if (!jsonObject.getString("mainHandleSignPic").startsWith("http")) {
                    jsonObject.put("mainHandleSignPic", ImageUtil.binaryImageWhite(jsonObject.getString("mainHandleSignPic")));
                } else {
                    jsonObject.put("mainHandleSignPic", ImageUtil.binaryImageWhite(ImageUtil.imageUrlTransBase64(jsonObject.getString("mainHandleSignPic"))));
                }
            }
            if (ObjectUtil.isNotEmpty(jsonObject.get("assistHandleSignPic"))) {
                if (!jsonObject.getString("assistHandleSignPic").startsWith("http")) {
                    jsonObject.put("assistHandleSignPic", ImageUtil.binaryImageWhite(jsonObject.getString("assistHandleSignPic")));
                } else {
                    jsonObject.put("assistHandleSignPic", ImageUtil.binaryImageWhite(ImageUtil.imageUrlTransBase64(jsonObject.getString("assistHandleSignPic"))));
                }
            }

            //URL地址转换成base64
            if (ObjectUtil.isNotEmpty(jsonObject.get(IMG_QR_CODE_URL))) {
                jsonObject.put("qrCodeUrl", ImageUtil.imageUrlTransBase64(jsonObject.getString(IMG_QR_CODE_URL)));
            }
            if (ObjectUtil.isNotEmpty(jsonObject.get(IMG_BAR_CODE_URL))) {
                jsonObject.put("barCodeUrl", ImageUtil.imageUrlTransBase64(jsonObject.getString(IMG_BAR_CODE_URL)));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
}
